package org.vacoor.xqq.ui.comp.tooltip;


import com.sun.awt.AWTUtilities;

import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.RoundRectangle2D;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 延迟显示 Tootip 窗口
 * <p/>
 *
 * @author: Vacoor
 */
public abstract class TooltipWindow extends JWindow {
    private Timer timer = new Timer();
    private TimerTask task;
    private volatile Boolean isShow;

    public TooltipWindow() {
        // 鼠标移动太快会造成, window无法隐藏, 这里暂时通过这种方式解决
        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseExited(MouseEvent e) {
                TooltipWindow.this.setVisible(false);
            }
        });
    }

    /**
     * 延迟显示
     */
    public void delayShow(long delay) {
        isShow = true;
        synchronized (this) {
            this.setContentPane(getDisplayComponent());
            if (task != null) {
                task.cancel();
            }
            task = new TimerTask() {
                @Override
                public void run() {
                    if (isShow) {
                        TooltipWindow.this.setVisible(isShow);
                        try {
                            AWTUtilities.setWindowOpacity(TooltipWindow.this, 0.92f);
                            //圆角
                            AWTUtilities.setWindowShape(TooltipWindow.this, new RoundRectangle2D.Double(0.0D, 0.0D, TooltipWindow.this.getWidth(), TooltipWindow.this.getHeight(), 5.0D, 5.0D));
                        } catch (Throwable e) {
                        }
                    }
                }
            };
        }
        timer.schedule(task, delay);
    }

    /**
     * 取消延迟显示
     */
    public void cancelDelayShow() {
        isShow = false;
        if (task != null) {
            task.cancel();
        }
    }

    protected abstract JComponent getDisplayComponent();
}
